# -*- coding: cp1251 -*-
import time
from PIL import Image
import sys,os
from PyQt4 import QtGui, QtCore, QtSvg
import stich
from stich import *
import getmap
from getmap import *
import thread


path=".\\map\\"
#path="C:\\_haven\\map\\longnames\\8\\"
stich.path=path
rty="R0000-00-0_00-00-00.png"
if not os.path.isdir(path):
        os.mkdir(path)
cleandict = True

saveUpd = saveUpdatedThread()
saveUpd.setDaemon(True)

def updateLastR (self):
    global rty
    if not os.path.isdir(path):
        os.mkdir(path)
    for file in os.listdir(path):
        if file[0]=='R':
            if file>rty:
                rty=file

def updateLastRthread (self):
    while True:
        updateLastR(self)
        time.sleep(2)


class MyView(QtGui.QGraphicsView):
    global path
    def __init__(self,*args):

        QtGui.QGraphicsView.__init__(self,*args)

        saveUpd.start()
        thread.start_new_thread(grabMapthread,(path,))
        thread.start_new_thread(updateLastRthread,(self,))
    def eventFilter(self, QObjec, event):
        if event.type() == QtCore.QEvent.Wheel:
            if event.delta () > 0:
                self.slotScaleup()
            else:
                self.slotScaledown()
            #m_pos = event.pos()
            #self.centerOn(self.mapToScene(m_pos))
            return True
        return False

    def slotReload (self):
        pix2 = scene.addPixmap(QtGui.QPixmap(path+rty))

        if (len( scene.items() ) > 2):
            while len(scene.items())>2:
                scene.removeItem(scene.items()[1])
                #pix2 = scene.addPixmap(QtGui.QPixmap(path+rty))
        ##print scene.items()

    def slotScaledown(self):
        self.scale(0.9,0.9)

    def slotScaleup(self):
        self.scale(1.1,1.1)


app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()
widget.resize(500,500)


scene = QtGui.QGraphicsScene(QtCore.QRectF(0,0,2000,2000))
scene.setBackgroundBrush(QtGui.QColor("black"))

view = MyView(scene)
#view.centerOn(875,875)
#qw=QtSvg.QSvgWidget(view)
#qw.load("hnher.svg")
#qw.move(-60,-150)

#qww=QtSvg.QGraphicsSvgItem("hnher.svg")
#scene.addItem(qww)
#pix2 = scene.addPixmap(QtGui.QPixmap("hnh.png"))
view.setDragMode(QtGui.QGraphicsView.ScrollHandDrag)

view.verticalScrollBar().installEventFilter(view)

timer = QtCore.QTimer()
timer.setInterval(2000)
timer.start()


#QtCore.QObject.connect(buttonDown ,QtCore.SIGNAL("clicked()"),view.slotScaledown)
#QtCore.QObject.connect(buttonUp,QtCore.SIGNAL("clicked()"),view.slotScaleup)
QtCore.QObject.connect(timer,QtCore.SIGNAL("timeout()"),view.slotReload)

layout=QtGui.QVBoxLayout()
layout.addWidget(view)
widget.setLayout(layout)

widget.show()
ax=app.exec_()
sys.exit(ax)

